package com.imonsoft.sqm.service.sys;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.imonsoft.common.constant.ConstantSqm;
import com.imonsoft.common.exception.SystemException;
import com.imonsoft.common.httpModel.DataGrid;
import com.imonsoft.common.httpModel.Pager;
import com.imonsoft.common.util.ListUtil;
import com.imonsoft.common.util.MD5Util;
import com.imonsoft.sqm.dao.sys.FunctionDAO;
import com.imonsoft.sqm.dao.sys.RoleDAO;
import com.imonsoft.sqm.dao.sys.UserDAO;
import com.imonsoft.sqm.dao.sys.UserRoleDAO;
import com.imonsoft.sqm.pojo.sys.Function;
import com.imonsoft.sqm.pojo.sys.Role;
import com.imonsoft.sqm.pojo.sys.User;
import com.imonsoft.sqm.pojo.sys.UserExample;
import com.imonsoft.sqm.pojo.sys.UserRole;
import com.imonsoft.sqm.pojo.sys.UserRoleExample;
import com.imonsoft.sqm.vo.sys.UserUntil;

@Service("userService")
public class UserServiceImpl implements UserService {
	protected final Log logger = LogFactory.getLog(getClass());
	@Autowired
	private UserDAO userDAO;
	@Autowired
	private FunctionDAO functionDAO;
	@Autowired
	private UserRoleDAO userRoleDAO;
	@Autowired
	private RoleDAO roleDAO;

	@Override
	public void deleteUser(List<Long> idList) {
		if (null == idList || idList.isEmpty()) {
			throw new SystemException(ConstantSqm.DATA_ERROR);
		}
		for (int i = 0; i < idList.size(); i++) {
			User user = userDAO.selectUserByPrimaryKey(idList.get(i));
			user.setState(ConstantSqm.STATUS_DELETE);
			userDAO.updateUserByPrimaryKey(user);
		}
	}

	@Override
	public List<User> findUserByCode(String code) {
		if (StringUtils.isEmpty(code)) {
			throw new SystemException(ConstantSqm.DATA_ERROR);
		}
		UserExample example = new UserExample();
		UserExample.Criteria criteria = example.createCriteria();
		if (!StringUtils.isEmpty(code)) {
			criteria.andCodeEqualTo(code);
		}
		List<User> userList = userDAO.selectUserByExample(example);
		return userList;
	}

	@Override
	public Long insert(User entity) {
		if (null == entity) {
			throw new SystemException(ConstantSqm.DATA_ERROR);
		}
		entity.setState(ConstantSqm.STATUS_NORMAL);
		entity.setPassword(MD5Util.encode(entity.getPassword()));
		return userDAO.insertUser(entity);
	}

	@Override
	public int update(User entity) {
		if (null == entity || null == entity.getId()) {
			throw new SystemException(ConstantSqm.DATA_ERROR);
		}
		User user = userDAO.selectUserByPrimaryKey(entity.getId());
		user.setCode(entity.getCode());
		user.setName(entity.getName());
		user.setMail(entity.getMail());
		user.setPhone(entity.getPhone());
		return userDAO.updateUserByPrimaryKey(user);
	}

	@Override
	public int delete(Long id) {
		if (null == id) {
			throw new SystemException(ConstantSqm.DATA_ERROR);
		}
		return userDAO.deleteUserByPrimaryKey(id);
	}

	@Override
	public User get(Long id) {
		if (null == id) {
			throw new SystemException(ConstantSqm.DATA_ERROR);
		}
		User user = userDAO.selectUserByPrimaryKey(id);
		return user;
	}

	@Override
	public List<User> findList(User entity) {
		UserExample example = new UserExample();
		UserExample.Criteria criteria = example.createCriteria();
		if (null != entity) {
			if (!StringUtils.isEmpty(entity.getCode())) {
				criteria.andCodeLike(entity.getCode() + "%");
			}
		}
		List<User> userList = userDAO.selectUserByExample(example);
		return userList;
	}

	@Override
	public DataGrid<User> getDataGrid(User entity, Pager pager) {
		UserExample example = new UserExample();
		example.setOrderByClause("id desc");
		UserExample.Criteria criteria = example.createCriteria();
		if (null != entity) {
			if (!StringUtils.isEmpty(entity.getCode())) {
				criteria.andCodeLike(entity.getCode() + "%");
			}
			if (!StringUtils.isEmpty(entity.getName())) {
				criteria.andNameLike(entity.getName() + "%");
			}
			if (!StringUtils.isEmpty(entity.getState())) {
				criteria.andStateEqualTo(entity.getState());
			}
		}
		return userDAO.getDataGrid(example, pager);
	}

	public boolean checkUser(User user) {
		if (user == null) {
			throw new SystemException(ConstantSqm.DATA_ERROR);
		}
		UserExample example = new UserExample();
		example.setOrderByClause("id desc");
		UserExample.Criteria criteria = example.createCriteria();
		criteria.andNameEqualTo(user.getName());
		criteria.andPasswordEqualTo(MD5Util.encode(user.getPassword()));
		criteria.andStateEqualTo(ConstantSqm.STATUS_NORMAL);
		User checkUser = ListUtil.getSingleResult(userDAO.selectUserByExample(example));
		if (checkUser == null) {
			throw new SystemException("用户名或者账号错误！");
		}
		List<Function> functins = getFunctionListByUserId(checkUser.getId());
		if (functins == null) {
			throw new SystemException("账号密码验证成功，但是没有权限，请联系系统管理员开通权限！");
		}
		UserUntil userUntil = new UserUntil();
		userUntil.setFunctionList(functins);
		BeanUtils.copyProperties(checkUser, userUntil);
		UserUntil.putUser2Session(userUntil);
		return true;
	}

	public List<Function> getFunctionListByUserId(Long userId) {
		if (userId == null) {
			return null;
		}
		return functionDAO.getFunctionListByUserId(userId);
	}

	@Override
	public void txSetUserRoles(User user, List<Long> roleList) {
		if (user == null || roleList == null) {
			throw new SystemException(ConstantSqm.DATA_ERROR);
		}
		user = get(user.getId());
		if (user == null) {
			throw new SystemException(ConstantSqm.DATA_ERROR);
		}
		UserRoleExample example = new UserRoleExample();
		UserRoleExample.Criteria criteria = example.createCriteria();
		criteria.andUserIdEqualTo(user.getId());
		userRoleDAO.deleteUserRoleByExample(example);
		for (Long roleId : roleList) {
			UserRole userRole = new UserRole();
			userRole.setRoleId(roleId);
			userRole.setUserId(user.getId());
			userRoleDAO.insertUserRole(userRole);
		}
	}

	@Override
	public List<Role> getRoleListByUserId(Long userId) {
		if (userId == null) {
			return null;
		}
		return roleDAO.getRoleListByUserId(userId);
	}
}
